package services

import (
	"errors"
	"fmt"
	"longmen/server/config/global"
	"longmen/server/pkg/common/helper/encrypt"
	"longmen/server/pkg/common/helper/util"
	"longmen/server/pkg/db/mysql/db_main"
	"longmen/server/pkg/db/mysql/models/models_main"
	"longmen/server/pkg/db/redis/cache"
	"time"

	"longmen/server/pkg/common/api_models"
)

func (s *Service) GetAccount(user *models_main.User) ([]*models_main.UserWithdrawAccount, error) {
	return db_main.GetUserWithdrawAccountsParam(map[string]interface{}{"uid": user.Id})
}

func (s *Service) EditCashAccount(r *api_models.EditCashAccountReq, user *models_main.User) (string, error) {
	fName := "EditCashAccount"
	smscode, err := db_main.GetSmscodeParam(map[string]interface{}{
		"mobile":      user.Account,
		"code":        r.Smscode,
		"status":      0,
		"create_time": map[string]interface{}{">": time.Now().Add(time.Duration(-30) * time.Minute)},
	}, "create_time desc")
	if err != nil {
		return "验证码有误或已过期", fmt.Errorf("%s%s", util.Convert(fName), err.Error())
	}
	if smscode.Id <= 0 {
		return "验证码有误或已过期", fmt.Errorf("%s 验证码有误或已过期", util.Convert(fName))
	}
	smscode.Status = 1
	err = db_main.UpdateSmscode(smscode)
	if err != nil {
		global.Log.Error("msg", "UpdateSmscode error", "err", err)
	}

	if r.Accountid > 0 {
		account, err := db_main.GetUserWithdrawAccountParam(map[string]interface{}{"id": r.Accountid, "uid": user.Id})
		if err != nil {
			return "", fmt.Errorf("%s%s", util.Convert(fName), err.Error())
		}
		if account.Id <= 0 {
			return "账户不存在", errors.New("账户不存在")
		}
		account.AlipayName, account.AlipayAccount = r.AlipayName, r.AlipayAccount
		err = db_main.UpdateUserWithdrawAccount([]string{"alipay_name", "alipay_account"}, account)
		if err != nil {
			return "", fmt.Errorf("%s%s", util.Convert(fName), err.Error())
		}
		return "", nil
	}
	account := &models_main.UserWithdrawAccount{Uid: user.Id, AlipayName: r.AlipayName, AlipayAccount: r.AlipayAccount}
	err = db_main.InsertUserWithdrawAccount(account)
	if err != nil {
		return "", fmt.Errorf("%s%s", util.Convert(fName), err.Error())
	}
	return "", nil
}

func (s *Service) GetAnchorWithdrawalsCount(uid int) (int64, error) {
	return db_main.GetAnchorWithdrawalsCount(map[string]interface{}{"uid": uid})
}

func (s *Service) GetAnchorWithdrawals(uid, page, size int) ([]*models_main.AnchorWithdrawals, error) {
	return db_main.GetAnchorWithdrawals(map[string]interface{}{"uid": uid}, "create_time desc", page, size)
}

/**
 * Author: Amer
 * Function: Banks
 * Description: 获取银行列表
 */
func (s *Service) Banks() ([]*models_main.Banks, error) {
	return db_main.Banks()
}

/**
*提款密码验证
 */
func (s *Service) VerifyWithdrawPass(req *api_models.UserWithdrawPass, user *models_main.User) error {
	fName := "Service AddWithdraw"
	password, err := encrypt.PwdDesECBEncrypt(user.Account, req.PayPassword)
	if err != nil {
		return fmt.Errorf("%s%s", util.Convert(fName), err.Error())
	}
	//判断支付密码
	if password != user.PayPassword {
		return errors.New("您的支付密码错误")
	}
	err = cache.SetUserWithdrawVerify(user.Id)
	if err != nil {
		return fmt.Errorf("%s%s", util.Convert(fName), err.Error())
	}
	return nil
}

/**
 * Author: Amer
 * Function: Service AddWithdraw
 * Description: 提交提现表单
 */
func (s *Service) AddWithdraw(req *api_models.UserWithdrawReq, user *models_main.User) error {
	fName := "Service AddWithdraw"
	//验证码
	err := s.CheckCode(user.Mobile, req.Smscode)
	if err != nil {
		return fmt.Errorf("%s%s", util.Convert(fName), err.Error())
	}
	str, err := cache.GetUserWithdrawVerify(user.Id)
	if err != nil || str == "" {
		return errors.New("提款密码未验证")
	}
	//判断是否有足够金额
	session := s.DB.Begin()
	user2, err := db_main.GetUserForUpdate(session, user.Id)
	if err != nil {
		session.Rollback()
		return fmt.Errorf("%s%s", util.Convert(fName), err.Error())
	}

	if req.ApplyAmount > user.ProfitDiamond {
		session.Rollback()
		return errors.New(global.Lang.T("insufficient_balance"))
	}

	return db_main.AddWithdraw(req, user2, session)
}

/**
 * Author: Amer
 * Function: Service Withdraws
 * Description: 提現記錄
 */
func (s *Service) Withdraws(req *api_models.WithdrawsReq, uid int) ([]*api_models.WithdrawsRsp, error) {
	if req.StartTime == "" {
		req.StartTime = "2021-01-01"
	}
	if req.EndTime == "" {
		req.EndTime = time.Now().Format("2006-01-02")
	}
	dd, _ := time.ParseDuration("24h")
	end, _ := time.Parse("2006-01-02", req.EndTime)
	condition := map[string]interface{}{
		"created_time": map[string]interface{}{"between": []interface{}{req.StartTime, end.Add(dd).String()}},
		"uid":          uid,
	}
	if req.Status < 4 {
		condition["status"] = req.Status
	}
	rsp := make([]*api_models.WithdrawsRsp, 0)
	list, err := db_main.Withdraws(condition, "created_time desc", req.Page, req.Size)
	if err != nil || len(list) == 0 {
		return rsp, err
	}
	for _, item := range list {
		tmp := &api_models.WithdrawsRsp{
			Status:          api_models.WithdrawStatus[item.Status],
			SerialNumber:    item.SerialNumber,
			CreatedTime:     item.CreatedTime.Format("2006-01-02 15:04"),
			ApplyAmount:     util.I2S(item.ApplyAmount),
			BankName:        item.BankName,
			BankcardAccount: item.BankcardAccount,
			Remark:          item.Remark,
		}
		rsp = append(rsp, tmp)
	}

	return rsp, nil
}
